package org.example.mq.dataCenter;

import org.example.mq.common.MqException;
import org.example.mq.mqserver.core.Binding;
import org.example.mq.mqserver.core.Exchange;
import org.example.mq.mqserver.core.MSGQueue;
import org.example.mq.mqserver.core.Message;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/*
* 对所有在硬件上面的操作进行封装
* */
public class DiskDataCenter {
    private DataBaseMange dataBaseMange = new DataBaseMange();
    private MessageFileManager messageFileManager = new MessageFileManager();

    /*
    * 初始化
    * */
    public void init(){
        dataBaseMange.init();
        messageFileManager.init();
    }

    /*
    * 封装交换机
    * */
    public void insertExchange(Exchange exchange){
        dataBaseMange.insertExchange(exchange);
    }

    public void deleteExchange(String exchangeName){
        dataBaseMange.deleteExchange(exchangeName);
    }

    public List<Exchange> selectAllExchange(){
        return dataBaseMange.selectAllExchange();
    }

    /*
    * 封装消息队列
    * */
    public void insertMSGQueue(MSGQueue msgQueue) throws IOException {
        dataBaseMange.insertMSGQueue(msgQueue);
        //还需要创建出对应的文件
        messageFileManager.createQueueFile(msgQueue.getName());
    }

    public void deleteMSGQueue(String msgQueueName) throws IOException {
        dataBaseMange.deleteMSGQueue(msgQueueName);
        messageFileManager.destroyFile(msgQueueName);
    }

    public List<MSGQueue> selectAllMSGQueue(){
        return dataBaseMange.selectAllMSGQueue();
    }

    /*
    * 封装绑定关系
    * */
    public void insertBinding(Binding binding){
        dataBaseMange.insertBinding(binding);
    }

    public void deleteBinding(Binding binding){
        dataBaseMange.deleteBinding(binding);
    }

    public List<Binding> selectAllBinding(){
        return dataBaseMange.selectAllBinding();
    }

    /*
    * 封装消息
    * */
    public void sendMessage(MSGQueue msgQueue, Message message) throws IOException, MqException {
        messageFileManager.sendMessage(msgQueue, message);
    }

    public void deleteMessage(MSGQueue msgQueue,Message message) throws IOException, ClassNotFoundException, MqException {
        messageFileManager.deleteMessage(msgQueue, message);
        if(messageFileManager.checkGC(msgQueue.getName())){
            messageFileManager.gc(msgQueue);
        }
    }

    public LinkedList<Message> selectAllMessage(MSGQueue msgQueue) throws IOException, MqException, ClassNotFoundException {
        return messageFileManager.loadAllMessageFromQueue(msgQueue.getName());
    }

}
